package Geometry;

public class _892_SurfaceAreaof3DShapes{
    //wrong answer, only consider the situation that no hole in the grid.
    public int surfaceArea_w(int[][] grid) {
        int len = grid.length;
        int leftSight = 0;
        int upSight = 0;
        int[] beforeSights = new int[len];
        int area = 0;
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                leftSight = Math.max(leftSight, grid[i][j]);
                beforeSights[i] = Math.max(beforeSights[i], grid[i][j]);
                if (grid[i][j] != 0) {
                    upSight++;
                }
            }
            area += (leftSight + upSight);
            leftSight = 0;
            upSight = 0;
        }
        //calculate the beforeSight's area
        int beforeSight = 0;
        for (int sight : beforeSights) {
            beforeSight += sight;
        }
        //up area is the mirror of down area, and so on, so multiply 2.
        return (area + beforeSight) * 2;
    }

    public int surfaceArea(int[][] grid) {
        int[] dr = {1, 0, -1, 0};
        int[] dc = {0, 1, 0, -1};
        int len = grid.length;
        int area = 0;
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                if (grid[i][j] > 0) {
                    area += 2;
                    for (int k = 0; k < 4; k++) {
                        int ddr = i + dr[k];
                        int ddc = j + dc[k];
                        int tsurface = 0;
                        if (-1 < ddr && ddr < len && -1 < ddc && ddc < len) {
                            tsurface = grid[ddr][ddc];
                        }
                        area += Math.max(grid[i][j] - tsurface, 0);

                    }
                }
            }
        }
        return area;
    }
}
